#!/usr/bin/env ruby
# Copyright (c) 2021-2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Huawei Technologies Co.,Ltd.

require 'erb'
require 'optparse'
require 'ostruct'

def check_option(optparser, options, key)
  return if options[key]

  puts "Missing option: --#{key}"
  puts optparser
  exit false
end

options = OpenStruct.new

optparser = OptionParser.new do |opts|
  opts.banner = 'Usage: ecmastdlib_inline_gen.rb [options]'

  opts.on('-t', '--template FILE', 'Template for file generation (required)')
  opts.on('-d', '--data FILE', 'Source data in binary format (required)')
  opts.on('-o', '--output FILE', 'Output file (default is stdout)')

  opts.on('-h', '--help', 'Prints this help') do
    puts opts
    exit
  end
end
optparser.parse!(into: options)

file_exist = false
if options[:data]
  file = File.open(options.data, "rb")
  file_exist = true
end

check_option(optparser, options, :template)
template = File.read(File.expand_path(options.template))
output = options.output ? File.open(File.expand_path(options.output), 'w') : $stdout
t = ERB.new(template, nil, '%-')
t.filename = options.template
output.write(t.result(binding))
output.close

if file_exist
  file.close
end
